﻿namespace Fiddler
{
    using Microsoft.Win32;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Net;
    using System.Net.NetworkInformation;
    using System.Runtime.InteropServices;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;

    internal static class FiddlerToolbar
    {
        private static bool _bCapturing;
        private static IntPtr _hInvertedWindow;
        private static int _iFilterPID;
        private static Utilities.RECT _rectInvertedWindow;
        private static object oShowHideLock = new object();
        private static ToolStripButton tsbRemoveEncodings = null;
        private static ToolStripButton tsbScreenshot = null;
        private static ToolStripButton tsbStreaming = null;
        private static ToolStripButton tsbWindowName = null;
        private static ToolStripLabel tslNetStat = null;
        private static ToolStripLabel tslProcessFilter = null;
        private static ToolStrip tstripMain = null;

        static FiddlerToolbar()
        {
            FiddlerApplication.Prefs.AddWatcher("fiddler.ui", new EventHandler<PrefChangeEventArgs>(FiddlerToolbar.HandlePrefChanged));
        }

        private static void _AddBrowserToList(ToolStripSplitButton oTSSB, string sTitle, string sExe)
        {
            oTSSB.DropDownItems.Add(sTitle).Click += delegate(object Sender, EventArgs oEA)
            {
                _LaunchBrowser(sExe);
            };
        }

        private static void _DoHide()
        {
            if (tstripMain != null)
            {
                lock (oShowHideLock)
                {
                    tsbWindowName = null;
                    tslNetStat = null;
                    tsbScreenshot = null;
                    tsbRemoveEncodings = null;
                    tsbStreaming = null;
                    tstripMain.Dispose();
                    tstripMain = null;
                    FiddlerApplication._iShowOnlyPID = 0;
                }
            }
        }

        private static void _DoShow()
        {
            if (tstripMain == null)
            {
                object obj2;
                bool boolPref = FiddlerApplication.Prefs.GetBoolPref("fiddler.ui.toolbar.ShowLabels", true);
                Monitor.Enter(obj2 = oShowHideLock);
                try
                {
                    ToolStripButton button;
                    tstripMain = new ToolStrip();
                    if (CONFIG.flFontSize >= 10f)
                    {
                        tstripMain.Font = new Font(tstripMain.Font.FontFamily, 10f);
                    }
                    tstripMain.SuspendLayout();
                    tstripMain.ImageList = FiddlerApplication.UI.imglToolbar;
                    tstripMain.GripStyle = ToolStripGripStyle.Hidden;
                    tstripMain.Renderer = new TSRenderWithoutBorder();
                    tstripMain.AllowItemReorder = true;
                    tstripMain.ShowItemToolTips = true;
                    if (CONFIG.bIsViewOnly)
                    {
                        tsbWindowName = new ToolStripButton("FiddlerViewer");
                        tsbWindowName.Font = new Font(tsbWindowName.Font, FontStyle.Bold);
                        tsbWindowName.Padding = new Padding(5, 0, 15, 0);
                        tsbWindowName.Click += delegate(object sender, EventArgs e)
                        {
                            string sTitle = frmPrompt.GetUserString("FiddlerViewer Name", "Enter a new title for this viewer:", tsbWindowName.Text, true);
                            if (sTitle != null)
                            {
                                SetViewerTitle(sTitle, sTitle);
                            }
                        };
                        tstripMain.Items.Add(tsbWindowName);
                    }
                    if ((Environment.OSVersion.Version.Major == 6) && (Environment.OSVersion.Version.Minor >= 2))
                    {
                        button = new ToolStripButton(boolPref ? "Win8 Config" : string.Empty);
                        button.ToolTipText = "The EnableLoopback tool permits Windows 8 Metro-style apps to use Fiddler.";
                        button.ImageKey = "Win8";
                        button.Click += delegate(object sender, EventArgs e)
                        {
                            string path = CONFIG.GetPath("App") + @"\EnableLoopback.exe";
                            if (!System.IO.File.Exists(path))
                            {
                                path = CONFIG.GetPath("App") + @"..\EnableLoopback\EnableLoopback.exe";
                            }
                            if (System.IO.File.Exists(path))
                            {
                                Utilities.RunExecutable(path, string.Empty);
                            }
                            else if (MessageBox.Show("The EnableLoopback utility is not installed.\n\nVisit http://fiddler2.com/r/?Win8EL to learn more?", "Utility Not Installed", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                            {
                                Utilities.LaunchHyperlink("http://fiddler2.com/r/?Win8EL");
                            }
                        };
                        tstripMain.Items.Add(button);
                    }
                    button = new ToolStripButton();
                    button.ToolTipText = "Add a comment to the selected sessions.";
                    button.ImageKey = "comment";
                    button.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actCommentSelectedSessions();
                    };
                    tstripMain.Items.Add(button);
                    button = new ToolStripButton(boolPref ? "Replay" : string.Empty);
                    button.ToolTipText = "Reissue the selected requests.\nHold CTRL to reissue unconditionally.\nHold SHIFT to reissue multiple times.";
                    button.ImageKey = "refresh";
                    button.Click += delegate(object sender, EventArgs e)
                    {
                        if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
                        {
                            FiddlerApplication.UI.actUnconditionallyReissueSelected();
                        }
                        else
                        {
                            FiddlerApplication.UI.actReissueSelected(false);
                        }
                    };
                    tstripMain.Items.Add(button);
                    ToolStripDropDownButton button2 = new ToolStripDropDownButton();
                    button2.ToolTipText = "Remove sessions from the session list.";
                    button2.ImageKey = "remove";
                    ((ToolStripDropDownMenu)button2.DropDown).ShowCheckMargin = false;
                    ((ToolStripDropDownMenu)button2.DropDown).ShowImageMargin = true;
                    ((ToolStripDropDownMenu)button2.DropDown).ImageList = FiddlerApplication.UI.imglToolbar;
                    ToolStripMenuItem item = new ToolStripMenuItem("Remove all");
                    item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                    item.ImageKey = "redbang";
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actRemoveAllSessions();
                    };
                    button2.DropDownItems.Add(item);
                    item = new ToolStripMenuItem("Images");
                    item.ImageKey = "image";
                    item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actSelectSessionsWithResponseHeaderValue("Content-Type", "image/");
                        FiddlerApplication.UI.actRemoveSelectedSessions();
                        FiddlerApplication.UI.sbpInfo.Text = "Removed all images.";
                    };
                    button2.DropDownItems.Add(item);
                    item = new ToolStripMenuItem("CONNECTs");
                    item.ImageKey = "lock";
                    item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actSelectSessionsMatchingCriteria(oSess => oSess.HTTPMethodIs("CONNECT"));
                        FiddlerApplication.UI.actRemoveSelectedSessions();
                        FiddlerApplication.UI.sbpInfo.Text = "Removed CONNECT tunnels";
                    };
                    button2.DropDownItems.Add(item);
                    item = new ToolStripMenuItem("Non-200s");
                    item.ImageKey = "info";
                    item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actSelectSessionsMatchingCriteria(oSess => (oSess.state >= SessionStates.Done) && (200 != oSess.responseCode));
                        FiddlerApplication.UI.actRemoveSelectedSessions();
                        FiddlerApplication.UI.sbpInfo.Text = "Removed all but HTTP/200 responses.";
                    };
                    button2.DropDownItems.Add(item);
                    item = new ToolStripMenuItem("Non-Browser");
                    item.ImageKey = "builder";
                    item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actSelectSessionsMatchingCriteria(delegate(Session oSess)
                        {
                            string str = oSess.oFlags["x-ProcessInfo"];
                            if (!string.IsNullOrEmpty(str))
                            {
                                return !Utilities.IsBrowserProcessName(str);
                            }
                            return true;
                        });
                        FiddlerApplication.UI.actRemoveSelectedSessions();
                        FiddlerApplication.UI.sbpInfo.Text = "Removed all but browser traffic.";
                    };
                    button2.DropDownItems.Add(item);
                    item = new ToolStripMenuItem("Complete && Unmarked");
                    item.ImageKey = "mark";
                    item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.TrimSessionList(0);
                        FiddlerApplication.UI.sbpInfo.Text = "Removed all completed & unmarked sessions.";
                    };
                    button2.DropDownItems.Add(item);
                    item = new ToolStripMenuItem("Duplicate response bodies");
                    item.ImageKey = "snowflake";
                    item.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        Session[] allSessions = FiddlerApplication.UI.GetAllSessions();
                        List<ListViewItem> list = new List<ListViewItem>();
                        Dictionary<int, object> dictionary = new Dictionary<int, object>();
                        using (SHA1 sha = SHA1.Create())
                        {
                            foreach (Session session in allSessions)
                            {
                                if (session.state >= SessionStates.Done)
                                {
                                    if ((session.responseBodyBytes == null) || (session.responseBodyBytes.Length < 1))
                                    {
                                        if (session.ViewItem != null)
                                        {
                                            list.Add(session.ViewItem);
                                        }
                                    }
                                    else
                                    {
                                       
                                        if (dictionary.TryGetValue(session.responseBodyBytes.Length, out obj2))
                                        {
                                            if (obj2 is Session)
                                            {
                                                List<string> list2 = new List<string>();
                                                string str = BitConverter.ToString(sha.ComputeHash(((Session)obj2).responseBodyBytes));
                                                list2.Add(str);
                                                obj2 = dictionary[session.responseBodyBytes.Length] = list2;
                                            }
                                            string _item = BitConverter.ToString(sha.ComputeHash(session.responseBodyBytes));
                                            List<string> list3 = (List<string>)obj2;
                                            if (list3.Contains(_item))
                                            {
                                                list.Add(session.ViewItem);
                                            }
                                            else
                                            {
                                                list3.Add(_item);
                                            }
                                        }
                                        else
                                        {
                                            dictionary[session.responseBodyBytes.Length] = session;
                                        }
                                    }
                                }
                            }
                        }
                        FiddlerApplication.SuppressReportUpdates = true;
                        FiddlerApplication.UI.lvSessions.BeginUpdate();
                        foreach (ListViewItem item2 in list)
                        {
                            item2.Remove();
                        }
                        if (FiddlerApplication.UI.lvSessions.FocusedItem != null)
                        {
                            FiddlerApplication.UI.lvSessions.FocusedItem.Selected = true;
                        }
                        FiddlerApplication.UI.lvSessions.EndUpdate();
                        FiddlerApplication.SuppressReportUpdates = false;
                        FiddlerApplication.UI.actUpdateInspector(true, true);
                        FiddlerApplication.UI.sbpInfo.Text = "Removed " + list.Count + " duplicate bodies.";
                    };
                    button2.DropDownItems.Add(item);
                    tstripMain.Items.Add(button2);
                    button = new ToolStripButton(boolPref ? "Resume" : string.Empty);
                    button.ToolTipText = "Resume all sessions that are currently stopped at breakpoints.";
                    button.ImageKey = "resume";
                    button.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actResumeAllSessions();
                    };
                    tstripMain.Items.Add(button);
                    ToolStripSeparator separator = new ToolStripSeparator();
                    tstripMain.Items.Add(separator);
                    tsbStreaming = new ToolStripButton(boolPref ? "Stream" : string.Empty);
                    tsbStreaming.ToolTipText = "When Streaming Mode is enabled, all breakpoints are skipped and all HTTP responses are streamed.";
                    tsbStreaming.ImageKey = "streaming";
                    tsbStreaming.Checked = !FiddlerApplication.Prefs.GetBoolPref("fiddler.ui.rules.bufferresponses", true);
                    tsbStreaming.CheckOnClick = true;
                    tsbStreaming.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.Prefs.SetBoolPref("fiddler.ui.rules.bufferresponses", !(sender as ToolStripButton).Checked);
                    };
                    tstripMain.Items.Add(tsbStreaming);
                    tsbRemoveEncodings = new ToolStripButton(boolPref ? "Decode" : string.Empty);
                    tsbRemoveEncodings.ToolTipText = "When enabled, all traffic is decompressed for easy viewing.";
                    tsbRemoveEncodings.ImageKey = "decoder";
                    tsbRemoveEncodings.CheckOnClick = true;
                    tsbRemoveEncodings.Checked = FiddlerApplication.Prefs.GetBoolPref("fiddler.ui.rules.removeencoding", false);
                    tsbRemoveEncodings.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.Prefs.SetBoolPref("fiddler.ui.rules.removeencoding", tsbRemoveEncodings.Checked);
                    };
                    tstripMain.Items.Add(tsbRemoveEncodings);
                    separator = new ToolStripSeparator();
                    tstripMain.Items.Add(separator);
                    ToolStripDropDownButton tsddbKeepOnly = new ToolStripDropDownButton();
                    int num = FiddlerApplication.Prefs.GetInt32Pref("fiddler.ui.rules.keeponly", 0);
                    if (num > 0)
                    {
                        tsddbKeepOnly.Text = string.Format("Keep: {0} sessions", num.ToString());
                        tsddbKeepOnly.BackColor = System.Drawing.Color.LightGreen;
                    }
                    else
                    {
                        tsddbKeepOnly.Text = "Keep: All sessions";
                        tsddbKeepOnly.BackColor = System.Drawing.Color.Transparent;
                    }
                    tsddbKeepOnly.ToolTipText = "Select the maximum number of sessions to keep.";
                    tsddbKeepOnly.Margin = new Padding(2, 0, 4, 0);
                    tsddbKeepOnly.ImageKey = string.Empty;
                    ((ToolStripDropDownMenu)tsddbKeepOnly.DropDown).ShowCheckMargin = false;
                    ((ToolStripDropDownMenu)tsddbKeepOnly.DropDown).ShowImageMargin = false;
                    int[] numArray = new int[] { 100, 250, 500, 0x3e8, 0x1388, 0x2710 };
                    foreach (int num2 in numArray)
                    {
                        int iLocalLimitForDelegateToCapture = num2;
                        item = new ToolStripMenuItem(num2 + " sessions");
                        item.DisplayStyle = ToolStripItemDisplayStyle.Text;
                        item.Click += delegate(object sender, EventArgs e)
                        {
                            FiddlerApplication.Prefs.SetInt32Pref("fiddler.ui.rules.keeponly", iLocalLimitForDelegateToCapture);
                            tsddbKeepOnly.Text = "Keep: " + (sender as ToolStripMenuItem).Text;
                            tsddbKeepOnly.BackColor = System.Drawing.Color.LightGreen;
                        };
                        tsddbKeepOnly.DropDownItems.Add(item);
                    }
                    item = new ToolStripMenuItem("All sessions");
                    item.DisplayStyle = ToolStripItemDisplayStyle.Text;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.Prefs.RemovePref("fiddler.ui.rules.keeponly");
                        tsddbKeepOnly.Text = "Keep: All sessions";
                        tsddbKeepOnly.BackColor = System.Drawing.Color.Transparent;
                    };
                    tsddbKeepOnly.DropDownItems.Add(item);
                    tstripMain.Items.Add(tsddbKeepOnly);
                    if (CONFIG.bMapSocketToProcess && !CONFIG.bIsViewOnly)
                    {
                        tslProcessFilter = new ToolStripLabel("Any Process");
                        tslProcessFilter.ForeColor = System.Drawing.Color.FromKnownColor(KnownColor.WindowText);
                        tslProcessFilter.MouseDown += delegate(object sender, MouseEventArgs e)
                        {
                            if (e.Button == MouseButtons.Right)
                            {
                                _bCapturing = false;
                                tstripMain.Cursor = Cursors.Default;
                                ClearProcessFilter();
                            }
                            else
                            {
                                tstripMain.Capture = true;
                                _bCapturing = true;
                                FiddlerApplication._iShowOnlyPID = _iFilterPID = 0;
                                tstripMain.Cursor = Cursors.Cross;
                                _hInvertedWindow = IntPtr.Zero;
                                tslProcessFilter.Font = new Font(tslProcessFilter.Font, FontStyle.Italic);
                                tslProcessFilter.Text = "pick target...";
                            }
                        };
                        tstripMain.MouseMove += delegate(object sender, MouseEventArgs e)
                        {
                            if (_bCapturing)
                            {
                                ShowHoveredApplication();
                            }
                        };
                        tslProcessFilter.MouseUp += delegate(object sender, MouseEventArgs e)
                        {
                            EndMouseCapture();
                        };
                        tstripMain.MouseUp += delegate(object sender, MouseEventArgs e)
                        {
                            EndMouseCapture();
                        };
                        tslProcessFilter.ImageKey = "crosshair";
                        tslProcessFilter.ToolTipText = "Drag this icon to a window to show traffic from only that process.\nRight-click to cancel the filter.";
                        tstripMain.Items.Add(tslProcessFilter);
                    }
                    button = new ToolStripButton(boolPref ? "Find" : string.Empty);
                    button.ToolTipText = "Find sessions containing specified content.";
                    button.ImageKey = "find";
                    button.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actDoFind();
                    };
                    tstripMain.Items.Add(button);
                    button = new ToolStripButton(boolPref ? "Save" : string.Empty);
                    button.ToolTipText = "Save all sessions in a .SAZ file.";
                    button.ImageKey = "save";
                    button.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actSaveAllSessions();
                    };
                    tstripMain.Items.Add(button);
                    separator = new ToolStripSeparator();
                    tstripMain.Items.Add(separator);
                    tsbScreenshot = new ToolStripButton();
                    tsbScreenshot.ToolTipText = "Add a screenshot to the capture\nHold SHIFT to skip countdown.";
                    tsbScreenshot.ImageKey = "camera";
                    tsbScreenshot.Click += delegate(object sender, EventArgs e)
                    {
                        if (string.IsNullOrEmpty(tsbScreenshot.Text))
                        {
                            bool flag = Keys.None != (Control.ModifierKeys & (Keys.Control | Keys.Shift));
                            FiddlerApplication.UI.actCaptureScreenshot(!flag);
                        }
                    };
                    tstripMain.Items.Add(tsbScreenshot);
                    ToolStripSplitButton button3 = new ToolStripSplitButton(boolPref ? "Browse" : string.Empty);
                    button3.ToolTipText = "Launch IE to the selected URL, or about:blank.";
                    button3.DropDownOpening += new EventHandler(FiddlerToolbar._fillBrowserList);
                    button3.ButtonClick += new EventHandler(FiddlerToolbar.tsbLaunchIE_Click);
                    button3.ImageKey = "ie";
                    tstripMain.Items.Add(button3);
                    if (!CONFIG.bIsViewOnly)
                    {
                        button = new ToolStripButton(boolPref ? "Clear Cache" : string.Empty);
                        button.ToolTipText = "Clear the WinINET cache. Hold CTRL to also delete persistent cookies.";
                        button.ImageKey = "clearcache";
                        button.Click += delegate(object sender, EventArgs e)
                        {
                            FiddlerApplication.UI.actClearWinINETCache();
                            if (Control.ModifierKeys == Keys.Control)
                            {
                                FiddlerApplication.UI.actClearWinINETCookies();
                            }
                        };
                        tstripMain.Items.Add(button);
                    }
                    button = new ToolStripButton(boolPref ? "TextWizard" : string.Empty);
                    button.ToolTipText = "Launch the TextWizard to encode/decode text.";
                    button.ImageKey = "tools";
                    button.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actShowTextWizard(null);
                    };
                    tstripMain.Items.Add(button);
                    separator = new ToolStripSeparator();
                    tstripMain.Items.Add(separator);
                    button = new ToolStripButton(boolPref ? "Tearoff" : string.Empty);
                    button.ToolTipText = "Open Details View in a floating window.";
                    button.ImageKey = "tearoff";
                    button.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actTearoffInspectors();
                    };
                    tstripMain.Items.Add(button);
                    separator = new ToolStripSeparator();
                    tstripMain.Items.Add(separator);
                    ToolStripTextBox tstbMSDN = new ToolStripTextBox("MSDNSearch");
                    Utilities.SetCueText(tstbMSDN.Control, "MSDN Search...");
                    tstbMSDN.AcceptsReturn = true;
                    tstbMSDN.KeyUp += delegate(object sender, KeyEventArgs e)
                    {
                        if (e.KeyCode == Keys.Return)
                        {
                            e.SuppressKeyPress = true;
                            e.Handled = true;
                            Utilities.LaunchHyperlink("http://social.msdn.microsoft.com/Search/en-US/?Refinement=59&Query=" + Utilities.UrlEncode(tstbMSDN.Text, Encoding.UTF8));
                        }
                    };
                    tstbMSDN.KeyDown += delegate(object sender, KeyEventArgs e)
                    {
                        if (e.KeyCode == Keys.Return)
                        {
                            e.SuppressKeyPress = true;
                        }
                        else if ((e.KeyCode == Keys.A) && (e.Modifiers == Keys.Control))
                        {
                            tstbMSDN.SelectAll();
                            e.SuppressKeyPress = true;
                            e.Handled = true;
                        }
                    };
                    tstripMain.Items.Add(tstbMSDN);
                    button = new ToolStripButton();
                    button.ToolTipText = "Show Fiddler's online help.";
                    button.ImageKey = "help";
                    button.Click += delegate(object sender, EventArgs e)
                    {
                        FiddlerApplication.UI.actGetHelp();
                    };
                    tstripMain.Items.Add(button);
                    button = new ToolStripButton();
                    button.ToolTipText = "Close this toolbar. Click View / Show Toolbar to get it back.";
                    button.ImageKey = "close";
                    button.Alignment = ToolStripItemAlignment.Right;
                    button.Click += delegate(object sender, EventArgs e)
                    {
                        Hide();
                    };
                    tstripMain.Items.Add(button);
                    tslNetStat = new ToolStripLabel("Detecting");
                    tslNetStat.Alignment = ToolStripItemAlignment.Right;
                    tslNetStat.BackColor = System.Drawing.Color.Transparent;
                    tslNetStat.ImageKey = "notconnected";
                    tslNetStat.ToolTipText = "Detecting network status...";
                    tslNetStat.MouseDown += delegate(object sender, MouseEventArgs e)
                    {
                        if (e.Clicks > 1)
                        {
                            Utilities.RunExecutable("control.exe", "netconnections");
                        }
                    };
                    tstripMain.Items.Add(tslNetStat);
                    UpdateNetworkStatus();
                    tstripMain.ResumeLayout();
                    FiddlerApplication.UI.Controls.Add(tstripMain);
                }
                catch (Exception exception)
                {
                    FiddlerApplication.ReportException(exception, "Toolbar failed");
                }
                finally
                {
                    Monitor.Exit(obj2);
                }
            }
        }

        private static void _fillBrowserList(object sender, EventArgs eA)
        {
            ToolStripSplitButton oTSSB = sender as ToolStripSplitButton;
            if (oTSSB != null)
            {
                ((ToolStripDropDownMenu)oTSSB.DropDown).ShowImageMargin = false;
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths", false);
                if (key != null)
                {
                    RegistryKey key2 = key.OpenSubKey("chrome.exe");
                    if (key2 != null)
                    {
                        _AddBrowserToList(oTSSB, "Chrome", "chrome.exe");
                        key2.Close();
                    }
                    key.Close();
                }
                RegistryKey key3 = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths", false);
                if (key3 != null)
                {
                    RegistryKey key4 = key3.OpenSubKey("iexplore.exe");
                    if (key4 != null)
                    {
                        _AddBrowserToList(oTSSB, "Internet Explorer", "iexplore.exe");
                        key4.Close();
                    }
                    key4 = key3.OpenSubKey("firefox.exe");
                    if (key4 != null)
                    {
                        _AddBrowserToList(oTSSB, "Firefox", "firefox.exe");
                        key4.Close();
                    }
                    key4 = key3.OpenSubKey("safari.exe");
                    if (key4 != null)
                    {
                        _AddBrowserToList(oTSSB, "Safari", "safari.exe");
                        key4.Close();
                    }
                    key3.Close();
                }
                string stringPref = FiddlerApplication.Prefs.GetStringPref("fiddler.ui.toolbar.BrowserList", null);
                if (!string.IsNullOrEmpty(stringPref))
                {
                    foreach (string str2 in stringPref.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        _AddBrowserToList(oTSSB, Utilities.TrimAfter(str2, '='), Utilities.TrimBefore(str2, '='));
                    }
                }
                oTSSB.DropDownOpening -= new EventHandler(FiddlerToolbar._fillBrowserList);
            }
        }

        private static void _LaunchBrowser(string sExe)
        {
            if (FiddlerApplication.UI.lvSessions.SelectedItems.Count == 1)
            {
                Utilities.RunExecutable(sExe, FiddlerApplication.UI.GetFirstSelectedSession().fullUrl);
            }
            else
            {
                Utilities.RunExecutable(sExe, "about:blank");
            }
        }

        internal static void ClearProcessFilter()
        {
            FiddlerApplication._iShowOnlyPID = _iFilterPID = 0;
            if (IsShowing())
            {
                tslProcessFilter.Text = "Any Process";
                tslProcessFilter.ForeColor = System.Drawing.Color.FromKnownColor(KnownColor.WindowText);
            }
        }

        internal static void DisplayIfNeeded()
        {
            if (FiddlerApplication.Prefs.GetBoolPref("fiddler.ui.toolbar.visible", true))
            {
                _DoShow();
            }
        }

        private static void EndMouseCapture()
        {
            if (_bCapturing)
            {
                _bCapturing = false;
                tstripMain.Cursor = Cursors.Default;
                tslProcessFilter.Font = new Font(tslProcessFilter.Font, FontStyle.Regular);
                FiddlerApplication._iShowOnlyPID = _iFilterPID;
                if (_iFilterPID == 0)
                {
                    tslProcessFilter.Text = "Any Process";
                    tslProcessFilter.ForeColor = System.Drawing.Color.FromKnownColor(KnownColor.WindowText);
                    FiddlerApplication.Log.LogString("Process filter cleared.");
                }
                else
                {
                    bool flag = Utilities.IsBrowserProcessName(tslProcessFilter.Text);
                    if (((CONFIG.iShowProcessFilter == ProcessFilterCategories.HideAll) || (flag && (CONFIG.iShowProcessFilter == ProcessFilterCategories.NonBrowsers))) || (!flag && (CONFIG.iShowProcessFilter == ProcessFilterCategories.Browsers)))
                    {
                        FiddlerApplication.UI._SetProcessFilter(ProcessFilterCategories.All);
                    }
                    tslProcessFilter.ForeColor = System.Drawing.Color.Red;
                    FiddlerApplication.Log.LogFormat(string.Format("Set to show traffic from only '{0}' HWND=0x{1:x}", tslProcessFilter.Text, (long)_hInvertedWindow), new object[0]);
                }
                RevertWindowMarking();
            }
        }

        [DllImport("user32.dll")]
        private static extern IntPtr GetWindowDC(IntPtr hWnd);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
        private static void HandlePrefChanged(object sender, PrefChangeEventArgs oPref)
        {
            if (oPref.PrefName == "fiddler.ui.toolbar.visible")
            {
                if (oPref.ValueBool)
                {
                    FiddlerApplication.UIInvoke(new MethodInvoker(FiddlerToolbar._DoShow));
                }
                else
                {
                    FiddlerApplication.UIInvoke(new MethodInvoker(FiddlerToolbar._DoHide));
                }
            }
            else if (oPref.PrefName == "fiddler.ui.rules.removeencoding")
            {
                if (tsbRemoveEncodings != null)
                {
                    bool valueBool = oPref.ValueBool;
                    tsbRemoveEncodings.Checked = valueBool;
                }
            }
            else if ((oPref.PrefName == "fiddler.ui.rules.bufferresponses") && (tsbStreaming != null))
            {
                bool flag3 = !oPref.ValueBool;
                tsbStreaming.Checked = flag3;
            }
        }

        internal static void Hide()
        {
            FiddlerApplication.Prefs.SetBoolPref("fiddler.ui.toolbar.visible", false);
        }

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll")]
        private static extern bool InvertRect(IntPtr hDC, [In] ref Utilities.RECT lprc);
        internal static bool IsShowing()
        {
            return (null != tstripMain);
        }

        private static string ProcessIDToProcessName(int iPid)
        {
            try
            {
                return Process.GetProcessById(iPid).ProcessName.ToLower();
            }
            catch
            {
                return string.Empty;
            }
        }

        [DllImport("user32.dll")]
        private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
        private static void RevertWindowMarking()
        {
            if (IntPtr.Zero != _hInvertedWindow)
            {
                IntPtr windowDC = GetWindowDC(_hInvertedWindow);
                InvertRect(windowDC, ref _rectInvertedWindow);
                ReleaseDC(_hInvertedWindow, windowDC);
                _hInvertedWindow = IntPtr.Zero;
            }
        }

        internal static void SetScreenshotCounter(string sText)
        {
            if ((tstripMain != null) && (tsbScreenshot != null))
            {
                tsbScreenshot.Text = sText;
            }
        }

        internal static void SetViewerTitle(string sTitle, string sTooltip)
        {
            if ((tstripMain != null) && (tsbWindowName != null))
            {
                tsbWindowName.Text = sTitle;
                tsbWindowName.ToolTipText = sTooltip;
                FiddlerApplication.UI.Text = "Fiddler Viewer - " + sTitle;
            }
        }

        internal static void Show()
        {
            FiddlerApplication.Prefs.SetBoolPref("fiddler.ui.toolbar.visible", true);
        }

        private static void ShowHoveredApplication()
        {
            try
            {
                IntPtr hWnd = WindowFromPoint(Cursor.Position);
                int lpdwProcessId = 0;
                GetWindowThreadProcessId(hWnd, out lpdwProcessId);
                if (hWnd != _hInvertedWindow)
                {
                    RevertWindowMarking();
                    if (Process.GetCurrentProcess().Id == lpdwProcessId)
                    {
                        tslProcessFilter.Text = "pick target...";
                        _iFilterPID = 0;
                    }
                    else
                    {
                        tslProcessFilter.Text = string.Format("{0}:{1}", ProcessIDToProcessName(lpdwProcessId), lpdwProcessId);
                        _iFilterPID = lpdwProcessId;
                        Utilities.GetWindowRect(hWnd, ref _rectInvertedWindow);
                        _rectInvertedWindow.Right -= _rectInvertedWindow.Left;
                        _rectInvertedWindow.Bottom -= _rectInvertedWindow.Top;
                        _rectInvertedWindow.Left = _rectInvertedWindow.Top = 0;
                        IntPtr windowDC = GetWindowDC(hWnd);
                        InvertRect(windowDC, ref _rectInvertedWindow);
                        ReleaseDC(hWnd, windowDC);
                        _hInvertedWindow = hWnd;
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private static void tsbLaunchIE_Click(object sender, EventArgs e)
        {
            _LaunchBrowser("iexplore.exe");
        }

        internal static void UpdateNetworkStatus()
        {
            if (tslNetStat != null)
            {
                if (FiddlerApplication.UI.InvokeRequired)
                {
                    FiddlerApplication.UIInvoke(new MethodInvoker(FiddlerToolbar.UpdateNetworkStatus));
                }
                else if (NetworkInterface.GetIsNetworkAvailable())
                {
                    try
                    {
                        IPAddress[] hostAddresses = Dns.GetHostAddresses(string.Empty);
                        StringBuilder builder = new StringBuilder();
                        foreach (IPAddress address in hostAddresses)
                        {
                            builder.AppendLine(address.ToString());
                        }
                        tslNetStat.ToolTipText = string.Format("Network connection active\nHost: {0}\nDomain: {1}\n\n{2}", CONFIG.sMachineName, CONFIG.sMachineDomain, builder.ToString());
                    }
                    catch (Exception)
                    {
                    }
                    tslNetStat.Text = "Online";
                    tslNetStat.ImageKey = "connected";
                }
                else
                {
                    tslNetStat.ToolTipText = "Network connection not active";
                    tslNetStat.Text = "Offline";
                    tslNetStat.ImageKey = "notconnected";
                }
            }
        }

        [DllImport("user32.dll")]
        private static extern IntPtr WindowFromPoint(Point pt);

        private class TSRenderWithoutBorder : ToolStripProfessionalRenderer
        {
            public TSRenderWithoutBorder()
            {
                base.RoundedEdges = false;
            }

            protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
            {
            }
        }
    }
}

